package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"

	"github.com/shxsun/beego/utils"
)

var (
	UploadAddr = flag.String("upload-addr", "http://localhost:8011/api/v1/add", "upload address")
)

func checkError(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

// upload data to data center
func UploadData(key, value string) {
	log.Println("upload", key, value)
	v := url.Values{}
	v.Add("path", key)
	v.Add("value", value)

	req, err := http.PostForm(*UploadAddr, v)
	defer req.Body.Close()
	if err != nil {
		log.Println(err)
	}
}

// call command
func CallInterval(interval time.Duration, command string, args ...string) {
	waitTime := time.Second * time.Duration(rand.Intn(5))
	log.Printf("%s %v: wait %s", command, args, waitTime)
	time.Sleep(waitTime)
	for {
		log.Printf("%s is calling", strconv.Quote(command))

		cmd := exec.Command(command, args...)
		cmd.Stderr = os.Stderr
		out, err := cmd.Output()
		if err != nil {
			log.Println(err)
		}
		lines := strings.Split(string(out), "\n")

		for _, line := range lines {
			if strings.TrimSpace(line) == "" {
				continue
			}
			var key, value string
			_, err = fmt.Sscanf(line, "%s%s", &key, &value)
			if err != nil {
				log.Println(err)
				goto SLEEP
			}
			go UploadData(key, value)
		}

	SLEEP:
		time.Sleep(interval)
	}
}

func main() {

	flag.Parse()

	filename, err := utils.LookFile("cron.conf", utils.SelfDir())
	checkError(err)

	fmt.Println(filename)
	lines, err := utils.GrepE(`^\s*[^#]+`, filename)
	checkError(err)
	for _, line := range lines {
		//time-gap, command
		kvs := strings.Fields(line)
		dur, err := time.ParseDuration(kvs[0])
		checkError(err)
		go CallInterval(dur, kvs[1], kvs[2:]...)
	}

	for {
		time.Sleep(10 * time.Minute)
	}
}
